<?php

declare(strict_types=1);

namespace app\common\model;

class ExamineTake extends Base
{

    protected $name = 'examine_take';
   
    public function user()
    {
        return $this->hasOne(User::class, 'id', 'uid')->field('id,rname,mobile');
    }
    /**
     * 开始答题
     */
    public static function startAnswer($param,$user)
    {
        try {
            $time = time();
            $sttime = $time-60*5;
            $info = Examine::where('id',$param['id'])->find();
            $cate = Cate::where('id',$info['cate'])->find();
            if(empty($info)){
                return ['code'=>-1,'msg'=>'考试不存在'];
            }
            if($time<$info['start_time']){
                return ['code'=>-1,'msg'=>'考试还未开始'];
            }else if($time>$info['end_time']){
                return ['code'=>-1,'msg'=>'考试已结束'];
            }else{
                if(md5($param['password']) != $info['password']){
                        return ['code'=>-1,'msg'=>'密码错误'];
                }
                $find = parent::where(['uid'=>$user->id,'examine_id'=>$param['id']])->find();
                if(empty($find)){
                    if($sttime>$info['start_time']){
                        return ['code'=>-1,'msg'=>'考试已开始！不可参加'];
                    }
                    $data=[
                        'uid'=>$user->id,
                        'examine_id'=>$param['id'],
                        'radio_num' => $cate['radio_num'],
                        'radio_score' => $cate['radio_score'],
                        'check_num' => $cate['check_num'],
                        'check_score' => $cate['check_score'],
                        'cate' => $cate['id'],
                    ];
                    parent::create($data);
                    ExamineBank::addBank($info,$user);
                }else{
                    if($find['status']!=3){
                        return ['code'=>-1,'msg'=>'您已交卷！不可考试'];
                    }
                }
                return ['code'=>1,'msg'=>'开始答题'];
            }
        }catch (\Exception $e){
            return ['code'=>-1,'msg'=>$e->getMessage()];
        }   
    }
}
